package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.api.RDeque;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private CartItemConverter converter;
    @Override
    public List<CartProductDto> getCartListById(Long userId) {
        String userId1 = userId.toString();
        RMap<Object, CartProductDto> map = redissonClient.getMap(userId1);

        List<CartProductDto> cartProductDtos = (List<CartProductDto>) map.readAllValues();
        return cartProductDtos;
    }

    @Override
    public void addToCart(CartRequest request) {
        Long userId = request.getUserId();
        Integer productNum = request.getProductNum();
        Long productId = request.getProductId();
        String userId1 = userId.toString();
        RMap<Object, CartProductDto> map = redissonClient.getMap(userId1);
        CartProductDto productDto = map.get(productId);
        if (productDto != null) {
            Long number = productDto.getProductNum() + productNum;
            productDto.setProductNum(number);
            map.put(productId, productDto);
            return;
        }
        Item item = itemMapper.selectByPrimaryKey(productId);
        CartProductDto cartProductDto = converter.item2Dto(item);
        cartProductDto.setChecked("true");
        long num =productNum;
        cartProductDto.setProductNum(num);
        map.put(productId, cartProductDto);
        return;
    }

    @Override
    public void updateCartNum(CartRequest request) {

    }

    @Override
    public void checkAllCartItem(CheckAllItemRequest request) {

    }

    @Override
    public void deleteCartItem(Long uid, Long itemId) {

    }

    @Override
    public void deleteCheckedItem(Long userId) {

    }
}
